﻿using System;
using System.ComponentModel.DataAnnotations;

namespace zijian666.ComponentModel.DataAnnotations;

/// <summary>
/// 不允许默认值
/// </summary>
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false)]
public class NotDefaultAttribute : ValidationAttribute
{
    private readonly object? _defaultValue;

    private object? GetDefaultValue(Type type)
    {
        if (!type.IsValueType)
        {
            return null;
        }
        type = Nullable.GetUnderlyingType(type) ?? type;
        if (type == typeof(DBNull))
        {
            return DBNull.Value;
        }
        return Activator.CreateInstance(type);
    }
    public NotDefaultAttribute()
    {
        ErrorMessage = "字段 {0} 不能是初始值";
    }

    public NotDefaultAttribute(Type type)
        : this()
    {
        if (type is null)
        {
            throw new ArgumentNullException(nameof(type));
        }
        _defaultValue = GetDefaultValue(type) ?? throw new ArgumentOutOfRangeException(nameof(type), nameof(type) + " 必须是结构体");
    }

    public override bool IsValid(object value)
    {
        if (value is null)
        {
            return _defaultValue is not null;
        }
        return value.Equals(_defaultValue ?? GetDefaultValue(value.GetType())) == false;
    }
}